package top.luoyuanxiang.personalknowledgebase.service.impl;

import com.alibaba.fastjson.JSON;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import top.luoyuanxiang.personalknowledgebase.entity.ChatSession;
import top.luoyuanxiang.personalknowledgebase.service.IChatSessionService;

import java.util.List;

/**
 * 会话服务
 *
 * @author luoyuanxiang
 */
@Service
public class ChatSessionServiceImpl implements IChatSessionService {

    public static final String CHAT_SESSION_PREFIX = "chat_session:";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void saveSession(ChatSession chatSession, String userId) {
        String key = CHAT_SESSION_PREFIX + userId;
        stringRedisTemplate.opsForList().leftPush(key, JSON.toJSONString(chatSession));
    }


    @Override
    public List<ChatSession> getSessions(String userId) {
        String key = CHAT_SESSION_PREFIX + userId;
        List<String> strings = stringRedisTemplate.opsForList().range(key, 0, -1);
        if (strings != null) {
            return strings.stream().map(s -> JSON.parseObject(s, ChatSession.class)).toList();
        }
        return List.of();
    }
}
